/* 
 * Copyright 2011-2012 Andrew Brock
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.catchwa.myvideobrowser.api;

import com.moviejukebox.themoviedb.MovieDbException;
import com.moviejukebox.themoviedb.TheMovieDb;
import com.moviejukebox.themoviedb.model.Artwork;
import com.moviejukebox.themoviedb.model.ArtworkType;
import com.moviejukebox.themoviedb.model.MovieDb;
import java.io.File;
import java.util.List;
import org.apache.log4j.Logger;
import org.catchwa.myvideobrowser.model.AlternateMatch;
import org.catchwa.myvideobrowser.model.Movie;

/**
 *
 * @author Andrew Brock
 */
public class TheMovieDbApi {

  private static Logger log = Logger.getLogger(TheMovieDbApi.class);
  private TheMovieDb tmdb;

  public TheMovieDbApi() {
    try {
      tmdb = new TheMovieDb("75eb70005723e1d70b5c2eb09d4c2316");
    } catch (MovieDbException e) {
      log.error("Error creating TMDb API instance", e);
    }
  }

  public Movie getMovieFromFile(File file, Integer preferredId) {
    String movieTitle;
    if (file.isFile()) {
      movieTitle = file.getName().substring(0, file.getName().lastIndexOf("."));
    } else {
      movieTitle = file.getName();
    }

    MovieDb result = null;
    AlternateMatch[] alternateMatches = null;
    String posterUrl = null;
    try {
      List<MovieDb> results = tmdb.searchMovie(movieTitle, "en", true);
      if (results.isEmpty()) {
        //TODO: handle case where movie does not exist better than just ignoring them
        return null;
      }
      if (preferredId == null) {
        result = results.remove(0);
      } else {
        for (int i = 0; i < results.size(); i++) {
          if (results.get(i).getId() == preferredId.intValue()) {
            result = results.remove(i);
            i = results.size();
          }
        }
      }

      // Prefer English artwork
      List<Artwork> artwork = tmdb.getMovieImages(result.getId(), "en");
      // If none exists, use anything
      if (artwork.isEmpty()) {
        artwork = tmdb.getMovieImages(result.getId(), null);
      }
      for (int i = 0; i < artwork.size(); i++) {
        if (artwork.get(i).getArtworkType().equals(ArtworkType.POSTER)) {
          // Preferred width is 342 pixels
          int posterIndex = 3;
          while (posterUrl == null) {
            posterUrl = tmdb.createImageUrl(artwork.get(i).getFilePath(), tmdb.getConfiguration().getPosterSizes().get(posterIndex)).toString();
            nextPosterSize(posterIndex);
          }
          i = artwork.size();
        }
      }

      alternateMatches = new AlternateMatch[results.size()];
      for (int i = 0; i < alternateMatches.length; i++) {
        alternateMatches[i] = new AlternateMatch(results.get(i).getId(), results.get(i).getTitle(), results.get(i).getReleaseDate() == null ? null : results.get(i).getReleaseDate().substring(0, 4));
      }
      result = tmdb.getMovieInfo(result.getId(), "en");
    } catch (MovieDbException e) {
      log.error("Error pulling movie info from TMDb API", e);
    }
    return new Movie(file, result.getTitle(), result.getReleaseDate(), result.getOverview(), result.getVoteAverage(), result.getRuntime(), false, posterUrl, alternateMatches);
  }

  private static int nextPosterSize(int current) {
    // Poster size array is [w92, w154, w185, w342, w500, original]
    if (current == 3) {
      return 2;
    }
    if (current == 1) {
      return 0;
    }
    if (current == 0) {
      return 4;
    }
    if (current == 4) {
      return 5;
    }
    return 5;
  }
}
